package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.util.HashMap;
import java.util.Map;

/**
 * Returns a format string. This function is useful in combination with the
 * DATE_FORMAT() and the STR_TO_DATE() functions. The possible columnValueList
 * for the firstInNewCursor and second argList result in several possible format
 * strings (for the specifiers used, see the where in the DATE_FORMAT()
 * function description). ISO format refers to ISO 9075, not ISO 8601.
 */
public class GetFormat extends ScalarFunction {

    private static Map<String, String> formats = new HashMap<String, String>();

    static {
        formats.put("DATE_USA", "%m.%d.%Y");
        formats.put("DATE_JIS", "%Y-%m-%d");
        formats.put("DATE_ISO", "%Y-%m-%d");
        formats.put("DATE_EUR", "%d.%m.%Y");
        formats.put("DATE_INTERNAL", "%Y%m%d");
        formats.put("TIMESTAMP_USA", "%Y-%m-%d %H.%i.%s");
        formats.put("TIMESTAMP_JIS", "%Y-%m-%d %H.%i.%s");
        formats.put("TIMESTAMP_ISO", "%Y-%m-%d %H.%i.%s");
        formats.put("TIMESTAMP_EUR", "%Y-%m-%d %H.%i.%s");
        formats.put("TIMESTAMP_INTERNAL", "%Y%m%d%H%i%s");
        formats.put("TIME_USA", "%h:%i:%s %readPriority");
        formats.put("TIME_JIS", "%H:%i:%s");
        formats.put("TIME_ISO", "%H:%i:%s");
        formats.put("TIME_EUR", "%H:%i:%s");
        formats.put("TIME_INTERNAL", "%H%i%s");
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        String type = Type.StringType.convert(args[0]);
        String format = Type.StringType.convert(args[1]);
        return formats.get(type + "_" + format);
    }

    public Type getReturnType() {
        return Type.StringType;
    }

    public String[] getFunctionNames() {
        return new String[]{"get_format"};
    }
}
